/** @file sonar.c
 * @brief Control code for the MAXSONAR module
 *
 *    @author Unknown
 *    
 */

#include <avr/io.h>						// to access input and output port variables
#include <avr/interrupt.h>				// to access interrupt variables
#include <inttypes.h>					// defines integer functions
#include "radio.h"				// defines radio debugger functions
#include "sonar.h"						// defines sonar functions
#include "functions.h"					// defines general functions
#include <string.h>
#include <stdio.h>
#include "../uart.h"

static uint16_t time_falling = 0;		/**	holds time count when falling edge detected **/

int recieved = 0;

char buff[50];

void sonar_init(){

	//	initialize sonar
	DDRC |= SONAR_PULSE_MASK;			/**	enable output on pin 6, port C **/
	TCCR3B &= ~(_BV(CS32) | _BV(CS30));	/**	set clock source to prescale by 8 **/
	TCCR3B |= _BV(CS31);				/**	set clock source to prescale by 8 **/
	TCCR3B |= _BV(ICNC3);				/**	enable noise cancelling **/

	//	enable timer and global interrupts
	SET_RISING_EDGE();
	CLEAR_IC_FLAG();
	SET_IC_ENABLE();
	ENABLE_ECHO();
	sei();								/** enable global interrupts **/
	waitFor(250);
}

void trigger_sonar(){
	ENABLE_PULSE();
	SET_RISING_EDGE();
	CLEAR_IC_FLAG();
	SET_IC_ENABLE();
}

uint8_t read_distance() {
	
	//sprintf(buff, "Radio init time_falling:%d", time_falling);
	//uart_write((uint8_t*)buff, strlen(buff));
	
	return (time_falling/US_PER_INCH);	/** pulse width = 147 us/inch **/

}

ISR(TIMER3_CAPT_vect) {

	DISABLE_PULSE();					/** only read one pulse at a time **/
	recieved = 1;

	if (IS_RISING_EDGE()) {
		TCNT3=0;						/** reset timer counter for start of pulse **/
		SET_FALLING_EDGE();
		CLEAR_IC_FLAG();
	}
	else {
		time_falling = ICR3;			/** ICR3 = TCNT3 when interrupt detected **/
		SET_RISING_EDGE();
		CLEAR_IC_FLAG();
	}
}

int signal_recieved (){

	
	int x = recieved;
	recieved = 0;

	return x;

}
